package com.zky.gulimall.member.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description feign配置
 * @Author 张开源
 * @Date 2022/12/9 21:40
 * @Version 1.0
 **/
@Configuration
@Slf4j
public class FeignConfig {
    /**
     * 配置拦截器解决feign请求头header丢失问题，因为feign调用时新建立一个请求，没有带原来请求请求头中cookie信息的,session会话登陆时很重要
     *
     * @return
     */
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                log.warn("member feign 请求执行之前先进行 RequestInterceptor apply");
                //拿到刚进来的请求
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes != null) {
                    log.warn("member RequestInterceptor apply 线程：" + Thread.currentThread().getName());
                    //获取老请求
                    HttpServletRequest request = attributes.getRequest();
                    if (request != null) {
                        //同步旧请求头数据到新请求
                        requestTemplate.header("Cookie", request.getHeader("Cookie"));
                    }
                }

            }
        };
    }
}
